<template>
  <div class="drawer-class">
    <el-drawer v-model="drawer">
      <template #header>
        <p>分配角色用户</p>
      </template>
      <template #default>
        <el-form>
          <el-form-item label="用户姓名">
            <el-input disabled v-model="formData.userName"></el-input>
          </el-form-item>
        </el-form>
        <el-checkbox
          v-model="checkAll"
          :indeterminate="isIndeterminate"
          @change="handleCheckAllChange"
        >
          全选
        </el-checkbox>
        <el-checkbox-group
          v-model="formData.assignRoles"
          @change="handleCheckChange"
        >
          <el-checkbox
            v-for="role in allRolesList"
            :key="role.id"
            :label="role.id"
          >
            {{ role.roleName }}
          </el-checkbox>
        </el-checkbox-group>
      </template>
      <template #footer>
        <el-button @click="close">取消</el-button>
        <el-button type="primary" @click="submit">确定</el-button>
      </template>
    </el-drawer>
  </div>
</template>

<script lang="ts" setup name="RoleDrawer">
import { ref, reactive } from 'vue'
import { assignUserRole, getUserRole } from '@/api/acl/user'
import type { AclUser } from '@/api/acl/types'
import { ElMessage } from 'element-plus'

const checkAll = ref(false)
const isIndeterminate = ref(true)
const drawer = ref(false)
const formData = reactive<any>({
  userId: undefined,
  userName: '',
  assignRoles: [],
})

const handleCheckAllChange = (val: boolean) => {
  isIndeterminate.value = false
  if (val) {
    formData.assignRoles = allRolesList.value.map((item) => item.id)
  } else {
    formData.assignRoles = []
  }
}
const handleCheckChange = () => {
  if (formData.assignRoles.length === 0) {
    checkAll.value = false
    isIndeterminate.value = false
  } else if (formData.assignRoles.length === allRolesList.value.length) {
    checkAll.value = true
    isIndeterminate.value = false
  } else {
    checkAll.value = false
    isIndeterminate.value = true
  }
}

const allRolesList = ref<AclUser.RoleList>([])
//根据id获取用户角色
const getRoleById = async () => {
  const res = await getUserRole(formData.userId)
  allRolesList.value = res.data.allRolesList
  formData.assignRoles = res.data.assignRoles.map((item) => item.id)
}

const close = () => {
  drawer.value = false
}

const open = (row: AclUser.AddUserReq) => {
  drawer.value = true
  formData.userId = row.id
  formData.userName = row.username
  getRoleById()
}

defineExpose({
  open,
})
const emit = defineEmits(['success'])
const submit = async () => {
  await assignUserRole(formData.userId, formData.assignRoles)
  ElMessage.success('分配角色成功')
  close()
  emit('success')
}
</script>

<style scoped lang="scss">
.drawer-class :deep(.el-drawer__header) {
  padding: 0 20px;
  font-size: 16px;
}
</style>
